package com.shinhye.elephantsafe.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;

public class SystemInfoUtils {

	/**
	 * 
	 * @param context
	 * @param serviceName
	 * @return
	 */
	public static boolean isServiceRunning(Context context, String serviceName) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> runningServices = am.getRunningServices(100);
		for (RunningServiceInfo runningServiceInfo : runningServices) {
			String name = runningServiceInfo.service.getClassName();
			if(name.equals(serviceName)) {
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * 
	 * @param context
	 * @return Running Process count.
	 */
	public static int getRunningProcessCount(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		return am.getRunningAppProcesses().size();
	}
	
	/**
	 * Get available RAM in system.
	 * @param context
	 * @return Available RAM
	 */
	public static long getAvailRAM(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		MemoryInfo outInfo = new ActivityManager.MemoryInfo();
		am.getMemoryInfo(outInfo);
		return outInfo.availMem;
	}
	
	/**
	 * Get total RAM in system.
	 * @param context
	 * @return Total RAM, if 0 there is a error happened.
	 */
	public static long getTotalRAM(Context context) {
		//MemoryInfo.totalMem方法只能在4.1以上系统使用。
		//通过读取内存信息的文件"/proc/meminfo"获取总内存大小
		File file = new File("/proc/meminfo");
		StringBuffer sb;
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			String str = reader.readLine();
			sb = new StringBuffer();
			for(char ch : str.toCharArray()) {
				if(ch >= '0' && ch <= '9')
					sb.append(ch);
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return Long.parseLong(sb.toString()) * 1024l;
	}
}
